/*******************************************************************************
 * Copyright 2011-2012 Dik Grapendaal
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/
package sh.grapendaal.tsuushin.module.uno;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import sh.grapendaal.tsuushin.annotation.Callback;
import sh.grapendaal.tsuushin.annotation.InjectService;
import sh.grapendaal.tsuushin.annotation.Module;
import sh.grapendaal.tsuushin.core.Context;
import sh.grapendaal.tsuushin.message.IncomingMessage;
import sh.grapendaal.tsuushin.message.MessageType;
import sh.grapendaal.tsuushin.message.PrivateMessage;
import sh.grapendaal.tsuushin.module.uno.engine.UnoEngine;
import sh.grapendaal.tsuushin.module.uno.engine.impl.UnoFactory;
import sh.grapendaal.tsuushin.service.CommandService;

/**
 * Uno IRC module.
 */
@Module(author = "Dik Grapendaal", version = "0.0.1")
public class Uno {
	@InjectService
	private CommandService commandService;

	/**
	 * This keeps track of the running Uno games. The module supports running
	 * multiple Uno games at the same time, one per channel.
	 */
	private Map<String, UnoGame> games = new HashMap<String, UnoGame>();

	@Callback(type = MessageType.CHANNEL_MESSAGE)
	public void onPrivateMessage(Context context, IncomingMessage message) {
		PrivateMessage incoming = (PrivateMessage) message;

		String channel = incoming.getDestination().toLowerCase(UnoConstants.DEFAULT_LOCALE);

		if (!games.containsKey(channel)
				&& IrcInput.containsGameCreateCommand(this.commandService.getPrefix(), incoming.getContent())) {
			IrcInput input = new IrcInput(this.commandService.getPrefix());
			IrcOutput output = new IrcOutput();
			File dataDirectory = new File(UnoConstants.DATA_DIRECTORY, channel);
			
			UnoEngine engine = UnoFactory.createUnoEngine(input, output, dataDirectory);

			games.put(channel, new UnoGame(engine, input, output));
		}

		UnoGame game = games.get(channel);
		if (game != null) {
			game.getOutput().setContext(context);
			game.getOutput().setDestination(channel);
			game.getInput().processMessage(incoming);
			
			if (IrcInput.containsGameStopCommand(this.commandService.getPrefix(), incoming.getContent())) {
				this.games.remove(channel);
			}
		}
	}

}
